from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QScrollArea, QWidget, QFrame, QMenu, QAction
from PyQt5.QtCore import Qt, QSize, pyqtSignal
from PyQt5.QtGui import QPixmap, QPalette

class ThumbnailSidebar(QWidget):
    # 新增信号：通知删除指定页面
    delete_page_requested = pyqtSignal(int)
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()
        self._selected_index = -1
        self._thumb_widgets = []  # 存储所有缩略图部件，便于管理
        self._current_page = 0    # 当前选中的页码
    
    def init_ui(self):
        """初始化UI组件"""
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(2, 2, 2, 2)
        
        # 滚动区域
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        
        # 滚动区域内容部件
        self.scroll_content = QWidget()
        self.scroll_layout = QVBoxLayout(self.scroll_content)
        self.scroll_layout.setContentsMargins(5, 5, 5, 5)
        self.scroll_layout.setSpacing(8)
        self.scroll_layout.setAlignment(Qt.AlignTop)
        
        # 初始信息标签
        self.info_label = QLabel("打开PDF文件查看缩略图")
        self.info_label.setAlignment(Qt.AlignCenter)
        self.info_label.setWordWrap(True)
        self.scroll_layout.addWidget(self.info_label)
        
        # 设置滚动区域
        self.scroll_area.setWidget(self.scroll_content)
        main_layout.addWidget(self.scroll_area)
        
        # 设置尺寸
        self.setMinimumWidth(120)
        self.setMaximumWidth(200)
    
    def add_thumbnail(self, pixmap, page_num, click_callback):
        """添加缩略图部件，支持右键删除"""
        # 创建缩略图容器
        container = QWidget()
        container.setObjectName(f"thumb_container_{page_num}")
        container.setStyleSheet("""
            QWidget { border-radius: 3px; }
            QWidget[selected="true"] { border: 2px solid #2196F3; background-color: #E3F2FD; }
        """)
        container.setContextMenuPolicy(Qt.CustomContextMenu)
        container.customContextMenuRequested.connect(
            lambda pos, p=page_num: self.show_context_menu(pos, p, container)
        )
        
        # 布局
        layout = QVBoxLayout(container)
        layout.setContentsMargins(2, 2, 2, 2)
        layout.setSpacing(2)
        
        # 缩略图标签
        thumb_label = QLabel()
        thumb_label.setPixmap(pixmap.scaled(
            100, 150, Qt.KeepAspectRatio, Qt.SmoothTransformation
        ))
        thumb_label.setAlignment(Qt.AlignCenter)
        
        # 页码标签
        page_label = QLabel(f"第 {page_num + 1} 页")
        page_label.setAlignment(Qt.AlignCenter)
        page_label.setStyleSheet("font-size: 10px;")
        
        # 添加到容器
        layout.addWidget(thumb_label)
        layout.addWidget(page_label)
        
        # 点击事件
        container.mousePressEvent = lambda e, p=page_num: click_callback(p)
        
        # 添加到布局
        self.scroll_layout.addWidget(container)
        self._thumb_widgets.append(container)
        
        # 隐藏初始信息标签
        if self.info_label and not self.info_label.isHidden():
            self.info_label.hide()

    def show_context_menu(self, position, page_num, parent_widget):
        """显示右键菜单，包含删除选项"""
        menu = QMenu(self)
        
        # 删除页面动作
        delete_action = QAction("删除此页面", self)
        # 直接发送信号，不在这里弹确认（避免重复）
        delete_action.triggered.connect(lambda: self.delete_page_requested.emit(page_num))
        
        menu.addAction(delete_action)
        menu.exec_(parent_widget.mapToGlobal(position))
    
    # --- 修复：删除此处的QMessageBox，统一到InteractionManager处理确认 ---
    def confirm_delete(self, page_num):
        """仅发送删除信号，确认逻辑移到交互层"""
        self.delete_page_requested.emit(page_num)
    
    def clear_thumbnails(self):
        """清除所有缩略图，保留初始信息标签（修复版）"""
        # 清除所有缩略图部件
        for widget in self._thumb_widgets:
            if widget:
                self.scroll_layout.removeWidget(widget)
                widget.deleteLater()
        self._thumb_widgets.clear()
        self._selected_index = -1
        
        # 显示初始信息标签（使用PyQt5兼容的方式检查控件有效性）
        if self.info_label:
            # 检查标签是否还有父对象（PyQt5中判断控件是否有效的方式）
            if self.info_label.parent() is None:
                # 如果标签已被移除，重新创建并添加
                self.info_label = QLabel("打开PDF文件查看缩略图")
                self.info_label.setAlignment(Qt.AlignCenter)
                self.info_label.setWordWrap(True)
                self.scroll_layout.addWidget(self.info_label)
            else:
                # 确保标签在布局中并显示
                if self.info_label not in [self.scroll_layout.itemAt(i).widget() 
                                          for i in range(self.scroll_layout.count())]:
                    self.scroll_layout.addWidget(self.info_label)
            self.info_label.show()
    
    def set_selected(self, page_num):
        """设置选中的缩略图"""
        # 取消之前的选中状态
        if 0 <= self._selected_index < len(self._thumb_widgets):
            prev_widget = self._thumb_widgets[self._selected_index]
            prev_widget.setProperty("selected", False)
            prev_widget.style().unpolish(prev_widget)
            prev_widget.style().polish(prev_widget)
        
        # 设置新的选中状态
        if 0 <= page_num < len(self._thumb_widgets):
            self._selected_index = page_num
            widget = self._thumb_widgets[page_num]
            widget.setProperty("selected", True)
            widget.style().unpolish(widget)
            widget.style().polish(widget)
            
            # 滚动到选中的缩略图
            self.scroll_area.ensureWidgetVisible(widget)
    
    def is_empty(self):
        """判断是否没有缩略图"""
        return len(self._thumb_widgets) == 0

        # 添加：保存当前滚动位置
    def save_scroll_position(self):
        """保存当前滚动条位置"""
        return self.scroll_area.verticalScrollBar().value()
    
    # 添加：恢复滚动位置
    def restore_scroll_position(self, position):
        """恢复滚动条到指定位置"""
        self.scroll_area.verticalScrollBar().setValue(position)